package com.guojiang.guopicturebackend.controller;


import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.guojiang.guopicturebackend.annotation.AuthCheck;
import com.guojiang.guopicturebackend.api.aliyunai.AliYunAiApi;
import com.guojiang.guopicturebackend.api.aliyunai.model.CreateOutPaintingTaskResponse;
import com.guojiang.guopicturebackend.api.aliyunai.model.GetOutPaintingTaskResponse;
import com.guojiang.guopicturebackend.api.imagesearch.ImageSearchApiFacade;
import com.guojiang.guopicturebackend.api.imagesearch.model.ImageSearchResult;
import com.guojiang.guopicturebackend.common.BaseResponse;
import com.guojiang.guopicturebackend.common.DeleteRequest;
import com.guojiang.guopicturebackend.common.ResultUtils;
import com.guojiang.guopicturebackend.constant.UserConstant;
import com.guojiang.guopicturebackend.exception.ErrorCode;
import com.guojiang.guopicturebackend.exception.ThrowUtils;
import com.guojiang.guopicturebackend.manager.auth.SpaceUserAuthManager;
import com.guojiang.guopicturebackend.manager.auth.StpKit;
import com.guojiang.guopicturebackend.manager.auth.annotation.SaSpaceCheckPermission;
import com.guojiang.guopicturebackend.manager.auth.model.SpaceUserPermissionConstant;
import com.guojiang.guopicturebackend.model.dto.picture.*;
import com.guojiang.guopicturebackend.model.entity.Picture;
import com.guojiang.guopicturebackend.model.entity.Space;
import com.guojiang.guopicturebackend.model.entity.User;
import com.guojiang.guopicturebackend.model.enums.PictureReviewStatusEnum;
import com.guojiang.guopicturebackend.model.vo.picture.PictureFormatVO;
import com.guojiang.guopicturebackend.model.vo.picture.PictureTagCategoryVO;
import com.guojiang.guopicturebackend.model.vo.picture.PictureVO;
import com.guojiang.guopicturebackend.service.PictureService;
import com.guojiang.guopicturebackend.service.SpaceService;
import com.guojiang.guopicturebackend.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

@Slf4j
@RestController
@RequestMapping("/picture")
public class PictureController {

    @Resource
    private UserService userService;

    @Resource
    private PictureService pictureService;

    @Resource
    private SpaceService spaceService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private SpaceUserAuthManager spaceUserAuthManager;

    @Resource
    private AliYunAiApi aliYunAiApi;

    /**
     * 本地缓存 Caffeine
     */
    private final Cache<String, String> LOCAL_CACHE = Caffeine.newBuilder()
            .initialCapacity(1024)
            .maximumSize(10000L)
            // 缓存 5 - 10 分钟移除
            .expireAfterWrite(5L + RandomUtil.randomLong(0, 5), TimeUnit.MINUTES)
            .build();

    /**
     * 上传本地图片（支持重新上传，现阶段已经允许用户使用）
     *
     * @param multipartFile
     * @param pictureUploadRequest
     * @param request
     * @return
     */
    @PostMapping("/upload/file")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_UPLOAD)
    public BaseResponse<PictureVO> uploadPictureByFile(
            @RequestPart("file") MultipartFile multipartFile, PictureUploadRequest pictureUploadRequest,
            HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        PictureVO pictureVO = pictureService.uploadPicture(multipartFile, pictureUploadRequest, loginUser);
        return ResultUtils.success(pictureVO);
    }

    /**
     * 图片地址上传图片（支持重新上传，现阶段已经允许用户使用）
     *
     * @param pictureUploadRequest
     * @param request
     * @return
     */
    @PostMapping("/upload/url")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_UPLOAD)
    public BaseResponse<PictureVO> uploadPictureByUrl(
            @RequestBody PictureUploadRequest pictureUploadRequest,
            HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        String fileUrl = pictureUploadRequest.getFileUrl();
        PictureVO pictureVO = pictureService.uploadPicture(fileUrl, pictureUploadRequest, loginUser);
        return ResultUtils.success(pictureVO);
    }

    /**
     * 批量抓取并创建图片（仅管理员可用）
     *
     * @param pictureUploadByBatchRequest
     * @param request
     * @return
     */
    @PostMapping("/upload/batch")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Integer> uploadPictureByBatch(@RequestBody PictureUploadByBatchRequest pictureUploadByBatchRequest, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        int uploadCount = pictureService.uploadPictureByBatch(pictureUploadByBatchRequest, loginUser);
        return ResultUtils.success(uploadCount);
    }

    /**
     * 编辑图片（公共图库：图片创建者/管理员；非公共图库：图库管理者）
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_DELETE)
    public BaseResponse<Boolean> deletePicture(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        // 校验请求体是否正常
        ThrowUtils.throwIf(deleteRequest == null, ErrorCode.PARAMS_ERROR, "deleteRequest 为空");
        long deletePictureId = deleteRequest.getId();
        User loginUser = userService.getLoginUser(request);
        pictureService.deletePicture(deletePictureId, loginUser);
        return ResultUtils.success(true);
    }

    /**
     * 更新图片（仅管理员可用）
     *
     * @param pictureUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updatePicture(@RequestBody PictureUpdateRequest pictureUpdateRequest, HttpServletRequest request) {
        Long updatePictureId = pictureUpdateRequest.getId();
        // 判断更新请求体是否正常
        ThrowUtils.throwIf(pictureUpdateRequest == null || updatePictureId <= 0
                , ErrorCode.PARAMS_ERROR);
        // 判断要更新的图片是否存在，不存在无需更新
        Picture updatePicture = pictureService.getById(updatePictureId);
        ThrowUtils.throwIf(updatePicture == null, ErrorCode.NOT_FOUND_ERROR, "要更新的图片不存在");
        // 将实体类和 DTO 进行转换  
        Picture picture = new Picture();
        BeanUtils.copyProperties(pictureUpdateRequest, picture);
        // 注意将 list 转为 string  
        picture.setTags(JSONUtil.toJsonStr(pictureUpdateRequest.getTags()));
        // 设置更新时间
        picture.setUpdateTime(new Date());
        // 图片合法性校验
        pictureService.validPicture(picture);
        // 补充审核参数
        pictureService.fillReviewParams(picture, userService.getLoginUser(request));
        // 操作数据库  
        boolean updateResult = pictureService.updateById(picture);
        ThrowUtils.throwIf(!updateResult, ErrorCode.OPERATION_ERROR, "更新失败，系统错误");
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取图片（仅管理员可用）
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Picture> getPictureById(Long id) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR, "参数非法");
        // 查询数据库  
        Picture picture = pictureService.getById(id);
        ThrowUtils.throwIf(ObjUtil.isNull(picture), ErrorCode.NOT_FOUND_ERROR, "要获取的图片不存在");
        return ResultUtils.success(picture);
    }

    /**
     * 根据 id 获取图片视图
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<PictureVO> getPictureVOById(Long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR, "请求参数非法");
        // 用户未登录，无法根据 id 获取图片视图
        User loginUser = userService.getLoginUser(request);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.OPERATION_ERROR, "请先登录");
        Long loginUserId = loginUser.getId();
        Picture picture = pictureService.getById(id);
        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR, "图片已经被删除");
        // 空间权限校验
        Long spaceId = picture.getSpaceId();
        Space space = null;
        if (spaceId != null) {
            // Sa-Token 编程式鉴权
            boolean hasPermission = StpKit.SPACE.hasPermission(SpaceUserPermissionConstant.PICTURE_VIEW);
            ThrowUtils.throwIf(!hasPermission, ErrorCode.NO_AUTH_ERROR, "无权查看图片");
            // 未使用第三方鉴权框架的自定义鉴权
            // pictureService.checkPictureAuth(picture, loginUser);
            space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(space == null, ErrorCode.PARAMS_ERROR, "空间不存在");
        } else {
            // 如果是公共图库，获取图片的过审情况
            PictureReviewStatusEnum reviewStatusEnum = PictureReviewStatusEnum.getEnumByValue(picture.getReviewStatus());
            // 图片未过审，则只有管理员或者图片创建人能查看该图片信息
            // 图片过审，那么所有用户都可以查看该图片信息
            ThrowUtils.throwIf(!(userService.isAdmin(loginUser) || picture.getUserId().equals(loginUserId)
                    || PictureReviewStatusEnum.PASS.equals(reviewStatusEnum)), ErrorCode.NO_AUTH_ERROR, "无权操作图片");
        }
        List<String> permissionList = spaceUserAuthManager.getPermissionList(space, loginUser);
        PictureVO pictureVO = pictureService.getPictureVO(picture, request);
        pictureVO.setPermissionList(permissionList);
        return ResultUtils.success(pictureVO);
    }

    /**
     * 分页获取图片列表（仅管理员可用）
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Picture>> listPictureByPage(@RequestBody PictureQueryRequest pictureQueryRequest) {
        long current = pictureQueryRequest.getCurrent();
        long size = pictureQueryRequest.getPageSize();
        // 查询数据库  
        Page<Picture> picturePage = pictureService.page(new Page<>(current, size),
                pictureService.getQueryWrapper(pictureQueryRequest));
        return ResultUtils.success(picturePage);
    }

    /**
     * 分页获取图片视图
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<PictureVO>> listPictureVOByPage(@RequestBody PictureQueryRequest pictureQueryRequest,
                                                             HttpServletRequest request) {
        long current = pictureQueryRequest.getCurrent();
        long size = pictureQueryRequest.getPageSize();
        // 限制爬虫  
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 空间权限校验
        Long spaceId = pictureQueryRequest.getSpaceId();
        if (spaceId == null) {
            // 公开图库
            // 非管理员只能看到审核通过的数据
            pictureQueryRequest.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
            // 需要查询 spaceId == null 的情况
            pictureQueryRequest.setNullSpaceId(true);
        } else {
            Space space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "图库不存在");
            // 私有空间，进行 Sa-Token 鉴权
            // Sa-Token 编程式鉴权
            boolean hasPermission = StpKit.SPACE.hasPermission(SpaceUserPermissionConstant.PICTURE_VIEW);
            ThrowUtils.throwIf(!hasPermission, ErrorCode.NO_AUTH_ERROR, "无权查看图片");
            // 未使用第三方鉴权框架的自定义鉴权
            // User loginUser = userService.getLoginUser(request);
            // ThrowUtils.throwIf(!loginUser.getId().equals(space.getUserId()), ErrorCode.NO_AUTH_ERROR, "无权操作图片");
        }
        // 查询数据库  
        Page<Picture> picturePage = pictureService.page(new Page<>(current, size),
                pictureService.getQueryWrapper(pictureQueryRequest));
        // 获取封装类  
        return ResultUtils.success(pictureService.getPictureVOPage(picturePage, request));
    }

    /**
     * 分页获取图片视图（有缓存）
     */
    @PostMapping("/list/page/vo/cache")
    public BaseResponse<Page<PictureVO>> listPictureVOByPageWithCache(@RequestBody PictureQueryRequest pictureQueryRequest,
                                                                      HttpServletRequest request) {
        long current = pictureQueryRequest.getCurrent();
        long size = pictureQueryRequest.getPageSize();
        // 限制爬虫  
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 空间权限校验
        Long spaceId = pictureQueryRequest.getSpaceId();
        if (spaceId == null) {
            // 公开图库
            // 非管理员只能看到审核通过的数据
            pictureQueryRequest.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
            // 需要查询 spaceId == null 的情况
            pictureQueryRequest.setNullSpaceId(true);
        } else {
            User loginUser = userService.getLoginUser(request);
            Space space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "图库不存在");
            ThrowUtils.throwIf(!loginUser.getId().equals(space.getUserId()), ErrorCode.NO_AUTH_ERROR, "无权操作图片");
        }
        // 查询缓存，缓存中没有，再查询数据库
        // 构建查询缓存的 key
        String queryCondition = JSONUtil.toJsonStr(pictureQueryRequest);
        String hashKey = DigestUtils.md5DigestAsHex(queryCondition.getBytes());
        String cacheKey = String.format("listPictureVOByPage:%s", hashKey);
        // 1. 优先查询本地缓存
        String cachedValue = LOCAL_CACHE.getIfPresent(cacheKey);
        if (StrUtil.isNotBlank(cachedValue)) {
            // 缓存命中，将数据反序列化并返回
            Page<PictureVO> cachePage = JSONUtil.toBean(cachedValue, Page.class);
            return ResultUtils.success(cachePage);
        }
        // 2. 本地缓存未命中，操作Redis，从Redis缓存中查询
        ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
        cachedValue = opsForValue.get(cacheKey);
        if (StrUtil.isNotBlank(cachedValue)) {
            // 缓存命中，将数据反序列化
            Page<PictureVO> cachePage = JSONUtil.toBean(cachedValue, Page.class);
            return ResultUtils.success(cachePage);
        }
        // 4. 本地缓存、Redis缓存均未命中，查询数据库  
        Page<Picture> picturePage = pictureService.page(new Page<>(current, size),
                pictureService.getQueryWrapper(pictureQueryRequest));
        Page<PictureVO> pictureVOPage = pictureService.getPictureVOPage(picturePage, request);
        // 存入缓存前需要对数据序列化
        String cacheValue = JSONUtil.toJsonStr(pictureVOPage);
        // 写入本地缓存
        LOCAL_CACHE.put(cacheKey, cacheValue);
        // 设置Redis缓存过期时间，5-10分钟内随机（减少缓存雪崩的风险）
        int cacheExpireTime = 300 + RandomUtil.randomInt(0, 300);
        // 写入Redis缓存
        opsForValue.set(cacheKey, cacheValue, cacheExpireTime, TimeUnit.SECONDS);
        // 获取封装类  
        return ResultUtils.success(pictureVOPage);
    }

    /**
     * 编辑图片（公共图库：图片创建者/管理员；非公共空间：空间管理者）
     *
     * @param pictureEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_EDIT)
    public BaseResponse<Boolean> editPicture(@RequestBody PictureEditRequest pictureEditRequest, HttpServletRequest request) {
        long editPictureId = pictureEditRequest.getId();
        // 校验参数合法性
        ThrowUtils.throwIf(pictureEditRequest == null, ErrorCode.PARAMS_ERROR, "pictureEditRequest 为空");
        // 定义正则表达式，只允许汉字和英文字母
        Pattern pattern = Pattern.compile("^[a-zA-Z\\u4e00-\\u9fa5]+$");
        // 校验分类
        String category = pictureEditRequest.getCategory();
        ThrowUtils.throwIf(category != null && StrUtil.isNotBlank(category) && !pattern.matcher(category).matches()
                , ErrorCode.PARAMS_ERROR, "分类只能包含汉字和英文字母");
        List<String> tags = pictureEditRequest.getTags();
        // 校验标签
        if (tags != null || CollUtil.isNotEmpty(tags)) {
            for (String tag : tags) {
                ThrowUtils.throwIf(tag != null && StrUtil.isNotBlank(tag) && !pattern.matcher(tag).matches()
                        , ErrorCode.PARAMS_ERROR, "标签只能包含汉字和英文字母");
            }
        }
        // 如果请求编辑的标签不为空，判断大小是否超过6
        if (tags != null || CollUtil.isNotEmpty(tags)) {
            ThrowUtils.throwIf(pictureEditRequest.getTags().size() > 6, ErrorCode.PARAMS_ERROR, "标签数量至多6个，请适当减少");
        }
        User loginUser = userService.getLoginUser(request);
        pictureService.editPicture(pictureEditRequest, loginUser);
        return ResultUtils.success(true);
    }

    /**
     * 批量编辑图片命名规则、分类和标签（公共图库：图片创建者/管理员；非公共图库：图库管理者）
     *
     * @param pictureEditByBatchRequest
     * @param request
     * @return
     */
    @PostMapping("/edit/batch")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_EDIT)
    public BaseResponse<Boolean> editPictureByBatch(@RequestBody PictureEditByBatchRequest pictureEditByBatchRequest, HttpServletRequest request) {
        // 编辑请求体是否正常
        ThrowUtils.throwIf(pictureEditByBatchRequest == null, ErrorCode.PARAMS_ERROR, "pictureEditRequest 为空");
        // 如果请求编辑的标签不为空，判断大小是否超过6
        if (CollUtil.isNotEmpty(pictureEditByBatchRequest.getTags())) {
            ThrowUtils.throwIf(pictureEditByBatchRequest.getTags().size() > 6, ErrorCode.PARAMS_ERROR, "标签数量至多6个，请适当减少");
        }
        User loginUser = userService.getLoginUser(request);
        pictureService.editPictureByBatch(pictureEditByBatchRequest, loginUser);
        return ResultUtils.success(true);
    }

    /**
     * 获取常见的图片标签、分类列表
     *
     * @return
     */
    @GetMapping("/tag_category")
    public BaseResponse<PictureTagCategoryVO> listPictureTagCategory() {
        PictureTagCategoryVO pictureTagCategoryVO = new PictureTagCategoryVO();
        List<String> tagList = Arrays.asList(
                "搞笑", "生活", "高清", "艺术", "校园", "背景", "简历", "创意", "风景",
                "美食", "动物", "人物", "科技", "时尚", "运动", "旅游", "卡通", "复古",
                "简约", "梦幻", "励志", "商务", "节日", "自然", "抽象", "建筑", "花卉",
                "星空", "儿童", "手绘", "夜景", "汽车", "游戏", "电影", "音乐", "家居",
                "城市", "乡村", "宠物", "毕业", "庆典", "聚会", "会议", "健康", "养生",
                "健身", "瑜伽", "舞蹈", "乐器", "书法", "绘画", "手工", "摄影", "街拍",
                "古风", "日系", "欧美", "韩系", "中国风", "民族风", "科幻", "奇幻", "恐怖",
                "悬疑", "正能量", "小清新", "治愈系", "暗黑系", "赛博朋克", "蒸汽朋克");
        List<String> categoryList = Arrays.asList(
                "PPT模板", "表情包", "海报制作", "摄影作品", "艺术绘画", "卡通动漫", "自然风光",
                "人物肖像", "美食图片", "动物图片", "建筑景观", "科技产品", "时尚潮流", "运动场景",
                "旅游风景", "家居生活", "教育学习", "医疗健康", "商业广告", "游戏画面", "影视截图",
                "音乐相关", "节日庆典", "历史文化", "军事装备", "植物花卉", "星空宇宙", "夜景灯光",
                "交通工具", "手工艺品", "抽象图案", "纹理背景", "图标标志", "电商带货", "地图图示",
                "工业设计", "创意合成", "古风古韵", "日系清新", "欧美风格", "韩系甜美", "中国风特色",
                "民族风情", "科幻奇幻", "恐怖悬疑", "励志正能量", "小清新治愈", "暗黑系风格", "赛博朋克风", "蒸汽朋克风");
        pictureTagCategoryVO.setTagList(tagList);
        pictureTagCategoryVO.setCategoryList(categoryList);
        return ResultUtils.success(pictureTagCategoryVO);
    }

    /**
     * 获取图片格式列表
     *
     * @return
     */
    @GetMapping("/format")
    public BaseResponse<PictureFormatVO> listPictureFormat() {
        PictureFormatVO pictureFormatVO = new PictureFormatVO();
        List<String> formatList = Arrays.asList("JPG", "PNG", "WEBP", "JPEG", "BMP");
        pictureFormatVO.setFormatList(formatList);
        return ResultUtils.success(pictureFormatVO);
    }

    /**
     * 审核图片（仅管理员可用）
     *
     * @param pictureReviewRequest
     * @param request
     * @return
     */
    @PostMapping("/review")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> doPictureReview(@RequestBody PictureReviewRequest pictureReviewRequest, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        pictureService.doPictureReview(pictureReviewRequest, loginUser);
        return ResultUtils.success(true);
    }

    /**
     * 果酱识图
     *
     * @param searchPictureByPictureRequest
     * @return
     */
    @PostMapping("/search/picture")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_VIEW)
    public BaseResponse<List<ImageSearchResult>> searchPictureByPicture(@RequestBody SearchPictureByPictureRequest searchPictureByPictureRequest) {
        ThrowUtils.throwIf(searchPictureByPictureRequest == null
                , ErrorCode.PARAMS_ERROR, "searchPictureByPictureRequest 为空");
        Long pictureId = searchPictureByPictureRequest.getPictureId();
        ThrowUtils.throwIf(pictureId == null || pictureId <= 0, ErrorCode.PARAMS_ERROR, "原图参数非法");
        Picture picture = pictureService.getById(pictureId);
        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR, "原图不存在");
        List<ImageSearchResult> imageSearchResultList = ImageSearchApiFacade.searchImage(picture.getOriginUrl());
        return ResultUtils.success(imageSearchResultList);
    }

    /**
     * 主色调搜索相似图片
     *
     * @param searchPictureByColorRequest
     * @param request
     * @return
     */
    @PostMapping("/search/color")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_VIEW)
    public BaseResponse<List<PictureVO>> searchPictureByColor(@RequestBody SearchPictureByColorRequest searchPictureByColorRequest
            , HttpServletRequest request) {
        ThrowUtils.throwIf(searchPictureByColorRequest == null
                , ErrorCode.PARAMS_ERROR, "searchPictureByPictureRequest 为空");
        User loginUser = userService.getLoginUser(request);
        List<PictureVO> pictureVOList = pictureService.searchPictureByColor(searchPictureByColorRequest.getSpaceId()
                , searchPictureByColorRequest.getPicColor(), loginUser);
        return ResultUtils.success(pictureVOList);
    }

    /**
     * 主色调搜索相似图片（管理员使用）
     *
     * @param searchPictureByColorRequest
     * @param request
     * @return
     */
    @PostMapping("/search/admin_color")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<List<Picture>> searchPictureForAdminByColor(@RequestBody SearchPictureByColorRequest searchPictureByColorRequest
            , HttpServletRequest request) {
        ThrowUtils.throwIf(searchPictureByColorRequest == null
                , ErrorCode.PARAMS_ERROR, "searchPictureByPictureRequest 为空");
        User loginUser = userService.getLoginUser(request);
        List<Picture> pictureList = pictureService.searchPictureForAdminByColor(searchPictureByColorRequest.getSpaceId()
                , searchPictureByColorRequest.getPicColor(), loginUser);
        return ResultUtils.success(pictureList);
    }

    /**
     * 创建 AI 扩图任务
     *
     * @param createPictureOutPaintingTaskRequest
     * @param request
     * @return
     */
    @PostMapping("/out_painting/create_task")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_EDIT)
    public BaseResponse<CreateOutPaintingTaskResponse> createPictureOutPaintingTask(@RequestBody CreatePictureOutPaintingTaskRequest createPictureOutPaintingTaskRequest
            , HttpServletRequest request) {
        ThrowUtils.throwIf(createPictureOutPaintingTaskRequest == null
                        || createPictureOutPaintingTaskRequest.getPictureId() == null
                        || createPictureOutPaintingTaskRequest.getPictureId() <= 0
                , ErrorCode.PARAMS_ERROR, "扩图任务请求参数无效");
        User loginUser = userService.getLoginUser(request);
        CreateOutPaintingTaskResponse createOutPaintingTaskResponse = pictureService.createPictureOutPaintingTask(createPictureOutPaintingTaskRequest, loginUser);
        return ResultUtils.success(createOutPaintingTaskResponse);
    }

    /**
     * 查询 AI 扩图任务
     *
     * @param taskId
     * @return
     */
    @GetMapping("/out_painting/get_task")
    public BaseResponse<GetOutPaintingTaskResponse> getPictureOutPaintingTask(String taskId) {
        ThrowUtils.throwIf(StrUtil.isBlank(taskId), ErrorCode.PARAMS_ERROR, "查询扩图任务结果请求参数为空");
        GetOutPaintingTaskResponse task = aliYunAiApi.getOutPaintingTask(taskId);
        return ResultUtils.success(task);
    }
}